package com.traffic.between.service;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;

import com.traffic.between.config.BetweenProperties;
import com.traffic.between.util.SecurityUtil;

/**
 * 吉林联通 直连 接口返回的结果 即为开通结果。
 * @author hhh
 *
 */
public class HanYueServiceImpl {
	
	private static Logger logger = Logger.getLogger(HanYueServiceImpl.class);
	public static HanYueServiceImpl service = new HanYueServiceImpl();
	
	private static String HOST_ORDER_PATH = BetweenProperties.HANYUE_ORDER_URL;
	private static String HANYUE_APPKEY = BetweenProperties.HANYUE_APPKEY;
	private static String HANYUE_SECURITYKEY = BetweenProperties.HANYUE_SECURITYKEY;
	
	
    //pkgNo, phoneNo, transNo
	public String order(String pkgNo, String phoneNo, String transNo) {
		
        String result = "";
        String appkey = HANYUE_APPKEY;
        String v = "1.0";
        String method = "services.order";
        String mobile = phoneNo;
        String productId = pkgNo;
      
        Map<String, String> requestData = new HashMap<String, String>();
        requestData.put("v", v);
        requestData.put("mobile",mobile);
        requestData.put("method",method);
        requestData.put("productId",productId);
        requestData.put("appkey",appkey);
        String waitSign = encryValueMap(requestData)+HANYUE_SECURITYKEY;
		try {
			String sign = SecurityUtil.shaEncoding(waitSign, "utf-8");
			List<BasicNameValuePair> pairList = new ArrayList<BasicNameValuePair>();
			pairList.add(new BasicNameValuePair("v", v));
			pairList.add(new BasicNameValuePair("appkey", appkey));
			pairList.add(new BasicNameValuePair("productId", productId));
			pairList.add(new BasicNameValuePair("method", method));
			pairList.add(new BasicNameValuePair("sign", sign));
			pairList.add(new BasicNameValuePair("mobile", mobile));
			logger.info("瀚悦订单请求参数：" + pairList);
			HttpPost httpPost = new HttpPost(HOST_ORDER_PATH);
			CloseableHttpClient client = HttpClients.createDefault();
			RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(25000).setConnectTimeout(25000).build();// 设置请求和传输超时时间
			httpPost.setConfig(requestConfig);
			httpPost.setEntity(new UrlEncodedFormEntity(pairList, "utf-8"));
			HttpResponse response = client.execute(httpPost);
			HttpEntity entity = response.getEntity();
			result = EntityUtils.toString(entity, "utf-8");
			logger.info("瀚悦订单请求返回参数：" + result);
		} catch (Exception e) {
			logger.info("瀚悦订单订购请求异常：" + e.getMessage());
		}
       
		return result;
	}

	/**
	 * @param surl
	 * @param params
	 *            如："username=kevin&password=12345"
	 * @return
	 */
	public String httpPost(String surl, String params) throws Exception {
		String sTotalString = "";
		try {
			URL url = new URL(surl);
			URLConnection connection = url.openConnection();
			System.setProperty("sun.net.client.defaultConnectTimeout", "25000");
			System.setProperty("sun.net.client.defaultReadTimeout", "25000");
			connection.setRequestProperty("accept", "text/xml;");
			connection.setRequestProperty("content-type",
					"application/x-www-form-urlencoded");
			// connection.setRequestProperty("user-agent",
			// "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
			// 发送POST请求必须设置如下两行
			connection.setDoOutput(true);
			connection.setDoInput(true);
			OutputStreamWriter out = new OutputStreamWriter(
					connection.getOutputStream(), "UTF-8");
			// OutputStreamWriter out = new OutputStreamWriter(
			// connection.getOutputStream(), "UTF-8");
			// params = "aa=中国&"+params;
			out.write(params); // 向页面传递数据。post的关键所在！
			out.flush();
			out.close();
			// 一旦发送成功，用以下方法就可以得到服务器的回应：
			String sCurrentLine;
			sCurrentLine = "";
			InputStream l_urlStream;
			l_urlStream = connection.getInputStream();
			// 传说中的三层包装阿！
			BufferedReader l_reader = new BufferedReader(new InputStreamReader(
					l_urlStream, "UTF-8"));
			while ((sCurrentLine = l_reader.readLine()) != null) {
				sTotalString += sCurrentLine + "\r\n";

			}
		} catch (Exception e) {
			throw new Exception("网络异常，连接服务器失败，请稍后重试");
			// log.info("POST data failed:" + surl);
		}
		// System.out.println(sTotalString);
		return sTotalString;
	}

	// key - value 升序排列组合
	public static String encryValueMap(Map<String, String> requestData) {
		StringBuilder encryValue = new StringBuilder();
		Object[] keys = requestData.keySet().toArray();
		Arrays.sort(keys);// 升序
		for (Object key : keys) {
			encryValue.append(key).append(requestData.get(key));
		}
		return encryValue.toString();
	}
	
	public static void main(String[] args) {
		new HanYueServiceImpl().order("1819","15526888876","CX20170720163301");
	}
}
